package com.cskaoyan.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.mall.commons.result.TokenInfo;
import com.cskaoyan.mall.commons.util.jwt.JwtTokenUtils;
import com.cskaoyan.user.constants.UserRetCode;
import com.cskaoyan.user.converter.UserConverterMapper;
import com.cskaoyan.user.dal.entitys.Member;
import com.cskaoyan.user.dal.persistence.MemberMapper;
import com.cskaoyan.user.dto.LoginVerifyResult;
import com.cskaoyan.user.dto.UserLoginResponse;
import com.cskaoyan.user.form.UserLoginRequest;
import com.cskaoyan.user.service.ILoginService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import tk.mybatis.mapper.entity.Example;

@Service
public class UserLoginServiceImpl implements ILoginService {

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private UserConverterMapper userConverter;

    @Override
    public UserLoginResponse login(UserLoginRequest request) {
        String userName = request.getUserName();
        String userPwd = request.getUserPwd();
        String encrypt = DigestUtils.md5DigestAsHex(userPwd.getBytes());

        // 根据用户名密码找到用户
        // 密码需要对比密文
        Example memExample = new Example(Member.class);
        memExample.createCriteria().andEqualTo("username", userName)
                .andEqualTo("password", encrypt);
        Member member = memberMapper.selectOneByExample(memExample);
        // 用户找不到，说明用户名或密码错误
        if (member == null) {
            throw new BizException(UserRetCode.USERORPASSWORD_ERRROR.getCode(),
                    UserRetCode.USERORPASSWORD_ERRROR.getMessage());
        }

        // 校验激活状态
        String verified = member.getIsVerified();
        if ("N".equals(verified)) {
            throw new BizException(UserRetCode.USER_ISVERFIED_ERROR.getCode(),
                    UserRetCode.USER_ISVERFIED_ERROR.getMessage());
        }

        // 生成token
        TokenInfo tokenInfo = new TokenInfo(member.getId(), member.getUsername());
        String tokenMsg = JSON.toJSONString(tokenInfo);
        String token = JwtTokenUtils.builder().msg(tokenMsg).build().creatJwtToken();
        UserLoginResponse response = userConverter.member2LoginResp(member);
        response.setToken(token);
        return response;
    }

    @Override
    public LoginVerifyResult verify(Long uid) {
        Example memExample = new Example(Member.class);
        memExample.createCriteria().andEqualTo("id", uid);
        Member member = memberMapper.selectOneByExample(memExample);
        if (member == null) {
            throw new BizException(UserRetCode.USER_INFOR_INVALID.getCode(),
                    UserRetCode.USER_INFOR_INVALID.getMessage());
        }
        return new LoginVerifyResult(uid, member.getFile());
    }
}
